import React, { useState, useCallback } from 'react';
import { ModelInfo, TaskType } from '../types';
import { Button, Panel, FileUploader, ModelSelector } from './shared';
import { PlayIcon, TrashIcon } from './icons';
import { ollamaService } from '../services/geminiService';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';

const MOCK_MODELS: ModelInfo[] = [
    { id: 'resnext50_20240729_1030.pth', name: 'resnext50_20240729_1030.pth', createdAt: '2024-07-29' },
    { id: 'resnext50_20240728_1800.pth', name: 'resnext50_20240728_1800.pth', createdAt: '2024-07-28' },
];

const MOCK_TEST_RESULTS = [
    { name: '类别A', precision: 0.98, recall: 0.95, f1: 0.96 },
    { name: '类别B', precision: 0.92, recall: 0.94, f1: 0.93 },
    { name: '类别C', precision: 0.88, recall: 0.91, f1: 0.89 },
    { name: '类别D', precision: 0.99, recall: 0.98, f1: 0.98 },
];


interface TestModelViewProps {
  isGpuBusy: boolean;
  setIsGpuBusy: (isBusy: boolean) => void;
  setStatusMessage: (message: string) => void;
}

const TestModelView = ({ isGpuBusy, setIsGpuBusy, setStatusMessage }: TestModelViewProps) => {
  const [isRunning, setIsRunning] = useState(false);
  const [guidance, setGuidance] = useState<string>('系统待机中... 等待测试任务指令。');
  const [fileName, setFileName] = useState<string | null>(null);
  const [selectedModel, setSelectedModel] = useState<string | null>(null);
  const [testResults, setTestResults] = useState<any[] | null>(null);

  const clearState = useCallback(() => {
    setIsRunning(false);
    setIsGpuBusy(false);
    setGuidance('系统待机中... 等待测试任务指令。');
    setFileName(null);
    setSelectedModel(null);
    setTestResults(null);
    setStatusMessage('状态: 空闲');
  }, [setIsGpuBusy, setStatusMessage]);

  const handleStart = () => {
    if (!fileName || !selectedModel) {
      setStatusMessage('错误: 请先选择模型并上传测试JSON文件');
      return;
    }
    setIsRunning(true);
    setIsGpuBusy(true);
    setTestResults(null);
    setGuidance('正在进行模型测试并请求AI分析...');
    setStatusMessage('测试数据加载中...');

    // Simulate the local part of the test (loading data, running metrics)
    setTimeout(() => {
        setStatusMessage('本地测试指标计算完成，正在生成AI分析报告...');
        setTestResults(MOCK_TEST_RESULTS);
        
        ollamaService.analyzeTestReport().then(analysis => {
            setGuidance(analysis);
            setStatusMessage('测试完成！');
            setIsRunning(false);
            setIsGpuBusy(false);
        });
    }, 1000); // Simulate local test duration
  };

  const handleFileUpload = (file: File) => {
    setFileName(file.name);
    setStatusMessage(`文件已上传: ${file.name}`);
  };

  return (
    <div className="p-4 flex flex-col gap-4 h-full hacker-scrollbar overflow-y-auto">
      <Panel title="任务控制">
        <div className="flex flex-wrap gap-4 items-end">
            <ModelSelector models={MOCK_MODELS} selectedModel={selectedModel} onSelectModel={setSelectedModel} disabled={isRunning || isGpuBusy} />
            <div className="flex flex-col gap-2">
                <label className="text-sm text-green-300">上传数据</label>
                <FileUploader onFileUpload={handleFileUpload} buttonText="上传测试JSON" disabled={isRunning || isGpuBusy} />
            </div>
            {fileName && <span className="text-cyan-300 text-sm self-center pt-8">已加载: {fileName}</span>}
            <div className="flex-grow" />
            <Button onClick={handleStart} disabled={isRunning || isGpuBusy || !fileName || !selectedModel} icon={<PlayIcon className="w-4 h-4" />}>开始测试</Button>
            <Button onClick={clearState} disabled={isRunning} icon={<TrashIcon className="w-4 h-4" />}>清空</Button>
        </div>
      </Panel>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 flex-grow">
        <Panel title="测试结果指标" className="flex-grow">
            {testResults ? (
                <ResponsiveContainer width="100%" height={300}>
                    <BarChart data={testResults} margin={{ top: 5, right: 20, left: -10, bottom: 5 }}>
                        <CartesianGrid strokeDasharray="3 3" stroke="#00ff4133" />
                        <XAxis dataKey="name" stroke="#00ff41" tick={{ fill: '#9ca3af' }} />
                        <YAxis stroke="#00ff41" tick={{ fill: '#9ca3af' }} domain={[0,1]}/>
                        <Tooltip
                            contentStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.8)', borderColor: '#00ff41', color: '#00ff41' }}
                            labelStyle={{ color: '#ffffff' }}
                        />
                        <Legend wrapperStyle={{color: '#00ff41'}} />
                        <Bar dataKey="precision" fill="#00ffff" name="精确率" />
                        <Bar dataKey="recall" fill="#00ff41" name="召回率" />
                        <Bar dataKey="f1" fill="#ff4d4d" name="F1分数" />
                    </BarChart>
                </ResponsiveContainer>
            ) : (
                <div className="flex items-center justify-center h-full text-gray-500">等待测试完成以显示结果...</div>
            )}
        </Panel>

        <Panel title="智能分析报告" className="flex-grow">
          <div className="h-full whitespace-pre-wrap text-sm text-cyan-200 hacker-scrollbar overflow-y-auto" style={{maxHeight: '300px'}}>
              {guidance}
          </div>
        </Panel>
      </div>
    </div>
  );
};

export default TestModelView;